/*  GStruct: data structure helpers for Java
 *  Copyright (C) 2011 Giulio Franco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package gstruct.sequential.lazy;

import gstruct.extensions.Predicate;

import java.util.ConcurrentModificationException;
import java.util.Iterator;

/**
 * Iterable implementation that iterates over the elements
 * of a backing iterable to which a given {@link Predicate} applies.
 * 
 * The implementation does not replicate the backing collection,
 * but lazily iterates it.
 * This also mean iterators returned by this collection
 * might throw a {@link ConcurrentModificationException}
 * if the backing collection is modified during iteration.
 * 
 * Also, this collection inherits thread-safety from the backing collection.
 * @author Giulio Franco <giulio_franco@msn.com>
 *
 * @param <T>
 */
public class LazyCollection<T> implements Iterable<T> {

	private class LazyIterator implements Iterator<T>{
		private Iterator<T> baseIterator;
		private T nextElement;
		private boolean hasNext = true;

		private LazyIterator() {
			baseIterator = baseCollection.iterator();
			findNextElement();
		}
		
		private void findNextElement() {
			while (baseIterator.hasNext()) {
				nextElement = baseIterator.next();
				if (predicate.appliesTo(nextElement)) {
					return;
				}
			}
			hasNext = false;
		}
		
		@Override
		public boolean hasNext() {
			return hasNext;
		}

		@Override
		public T next() {
			T res = nextElement;
			findNextElement();
			return res;
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}
	}
	
	private final Iterable<T> baseCollection;
	private final Predicate<? super T> predicate;
	
	/**
	 * Creates an iterable that iterates through the elements
	 * of collections which satisfy predicate.
	 * @param collection	Backing Iterable collection 
	 * @param predicate		Filtering predicate
	 */
	public LazyCollection(Iterable<T> collection, Predicate<? super T> predicate) {
		this.baseCollection = collection;
		this.predicate = predicate;
	}
	
	@Override
	public Iterator<T> iterator() {
		return new LazyIterator();
	}

}
